<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="6">
          <el-form-item :label="$t('起始年份')" prop="startYear">
            <date-picker
              v-model="form.startYear"
              type="year"
              :clearable="false"
              value-format="yyyy"
              :placeholder="$t('起始年份')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('预测年份')" prop="forecastYear">
            <el-input-number v-model="form.forecastYear" :max="10" :min="1" :step-strictly="true" :step="1" :placeholder="$t('预测年份')" show-word-limit maxlength="5" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('周期')" prop="cycle">
            <dictSelect
              v-model="form.cycle"
              :placeholder="$t('周期')"
              :clearable="false"
              :disabled="isNotEmpty(form.id) && isNotEmpty(form.cycle)"
              dictionary="deal_indicator_cycle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <div style="margin-top: 4.6vh;">
            <el-button type="primary" size="mini" @click="generate(true)">{{ $t('生成表格') }}</el-button>
          </div>
        </el-col>
        <el-col :span="2">
          <div style="margin-top: 4.6vh;">
            <el-tooltip v-model="showEmailTip" :manual="true" :content="$t('请维护邮箱')" placement="top">
              <el-button type="success" size="mini" @click="emailOpenMethod">{{ $t('邮箱维护') }}</el-button>
            </el-tooltip>
          </div>
        </el-col>
        <el-col :span="2">
          <div v-if="isNotEmpty(form.id) && isNotEmpty(form.cycle)" style="margin-top: 4.6vh;">
            <el-button type="warning" size="mini" @click="specifiedFilling">{{ $t('指定填报') }}</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 数据JSON -->
      <div v-loading="dataLoading">
        <div v-if="form.operationalIndicatorsList && form.operationalIndicatorsList.length > 0">
          <div class="area-header">
            <span class="area-header-title">{{ $t('运营指标数据列表') }}</span>
          </div>
          <el-table
            :data="form.operationalIndicatorsList"
            border
            row-key="id"
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <!-- 指标 运营指标数据列表 -->
            <el-table-column :label="$t('指标')" align="left" class-name="table-tree" width="250" fixed="left">
              <template slot-scope="scope">
                <el-form-item>
                  <span v-show="scope.row.children !== undefined && scope.row.children !== null && scope.row.children.length > 0">{{ scope.row.indicators }}</span>
                  <el-input v-show="!(scope.row.children !== undefined && scope.row.children !== null && scope.row.children.length > 0)" v-model="scope.row.indicators" disabled />
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 季度 运营指标数据列表 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ -->
            <div>
              <el-table-column
                v-for="(item) in dynamicColumns"
                :key="item.prop"
                :label="$t(item.label)"
                :prop="item.prop"
                align="center"
                min-width="130"
              >
                <template v-slot="scope">
                  <el-form-item
                    v-if="!(scope.row.children !== undefined && scope.row.children !== null && scope.row.children.length > 0)"
                  >
                    <money
                      v-model="scope.row[item.prop]"
                      :placeholder="$t('指标值')"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </div>
            <!-- ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ -->
          </el-table>
        </div>
        <el-empty v-if="!(form.operationalIndicatorsList && form.operationalIndicatorsList.length > 0)" :description="$t('暂无数据')" />
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;margin-top: 20px;">
      <el-button v-hasPermi="'deal:indicator'" type="primary" @click="submitForm">{{ $t('保存') }}</el-button>
    </div>

    <!-- 数据填写邮箱维护  -->
    <el-dialog :title="$t('数据填写邮箱维护')" :visible.sync="emailOpen" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" width="600" style="height: 680px; width: 600px; margin: auto !important;" custom-class="dialogForm" append-to-body>
      <dealIndicatorDataEmail ref="dealIndicatorDataEmail" @sendEmail="sendEmail" />
    </el-dialog>

    <!-- 指定填报 -->
    <el-dialog :title="$t('指定周期填报')" :visible.sync="specifiedFillingOpen" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" width="800" style="height: 60%;width: 50%;margin: auto !important;z-index: 2001;" custom-class="dialogForm" append-to-body>
      <dealIndicatorDataAppoint ref="dealIndicatorDataAppoint" />
    </el-dialog>
  </div>
</template>

<script>
import dealIndicatorDataEmail from '@/views/deal/indicator/data/dealIndicatorDataEmail.vue'
import dealIndicatorDataAppoint from '@/views/deal/indicator/data/dealIndicatorDataAppoint.vue'
import {
  getDealIndicatorDataMainByDealId,
  saveDealIndicatorDataMain
} from '@/api/deal/indicator/data/dealIndicatorDataMain.js'
import { getAllData } from '@/api/deal/indicator/dealIndicatorPredict'

export default {
  components: {
    dealIndicatorDataEmail,
    dealIndicatorDataAppoint
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      dataLoading: false,
      // 表单校验
      rules: {
        startYear: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        forecastYear: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        cycle: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      emailOpen: false,
      specifiedFillingOpen: false,
      pageForecastYear: 1,
      pageStartYear: undefined,
      pageCycle: '',
      showEmailTip: false,
      titleColor: ['black', 'FF9E00FF', '00CEFFFF', '00C52DFF', '9500FFFF', 'black', 'FF9E00FF', '00CEFFFF', '00C52DFF', '9500FFFF'],
      dynamicColumns: []
    }
  },
  watch: {
  },
  created() {
    this.init()
  },
  methods: {
    // 初始化数据
     init() {
      this.loading = true
      getDealIndicatorDataMainByDealId(this.$route.query.id).then(response => {
        if (response.data !== null) {
          this.form = response.data
          this.pageForecastYear = parseInt(this.form.forecastYear)
          this.pageStartYear = parseInt(this.form.startYear)
          this.pageCycle = this.form.cycle
          // 先生称页面table, 再把值赋值上去
          this.$nextTick(() => {
            this.generate(false)
          })
        } else {
          this.reset()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: this.$route.query.id,
        companyId: this.$route.query.companyId,
        startYear: new Date().getFullYear().toString(),
        forecastYear: 1,
        cycle: 'year',
        dealIndicatorDataDetailList: [],
        operationalIndicatorsList: [],
        dealIndicatorEmail: {},
        remark: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 生成数据列表 */
    generate(isInit) {
      this.$refs['form'].validate(valid => {
        var _this = this
        if (valid && this.form.startYear && this.form.forecastYear && this.form.cycle) {
          if (this.form.id === undefined || this.form.id === null || this.form.id === '') {
            this.$confirm(this.$t('当前[周期]在保存后不能再修改, 是否继续?'), this.$t('提示'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            }).then(() => {
              _this.generateData(isInit)
            }).catch(() => {
            })
          } else {
            if (isInit) {
              this.$confirm(this.$t('如果模板指标发生过变动, 重新生成的指标将会与当前指标有差异, 请留意!'), this.$t('提示'), {
                confirmButtonText: this.$t('好的'),
                cancelButtonText: this.$t('取消'),
                type: 'info'
              }).then(() => {
                _this.generateData(isInit)
              }).catch(() => {
              })
            } else {
              this.generateData(isInit)
            }
          }
        }
      })
    },
    generateData(isInit) {
      // 赋值给页面所需数据
      this.pageForecastYear = parseInt(this.form.forecastYear)
      this.pageStartYear = parseInt(this.form.startYear)
      this.pageCycle = this.form.cycle

      // 获取运营指标下的所有指标
      this.form.operationalIndicatorsList = []
      this.dataLoading = true
      this.loading = true
      getAllData({ parentId: '0', businessId: this.form.id ? this.form.id : this.$route.query.companyId, companyId: this.$route.query.companyId, updateData: isInit }).then(response => {
        if (response.rows !== undefined && response.rows !== null) {
          this.form.operationalIndicatorsList = response.rows
          if (this.isNotEmpty(this.form.operationalIndicatorsList)) {
            var errMsg = []
            var newData = []
            this.form.operationalIndicatorsList.forEach(item => {
              if (this.isEmpty(item.children)) {
                errMsg.push(item.indicators)
              } else {
                item.needAdd = isInit
                newData.push(item)
              }
            })
            if (errMsg.length > 0) {
              this.msgWarning('[' + errMsg.join(', ') + ']没有二级指标, 请先添加!')
            }
            this.form.operationalIndicatorsList = newData
          }
          // 生成动态列
          this.generateColumn()
          this.analysisTableToVue()
        }
        this.loading = false
        this.dataLoading = false
      })
    },
    uuid() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4'
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
      s[8] = s[13] = s[18] = s[23] = '-'
      return s.join('').replaceAll('-', '')
    },
    /**
     * 生成动态列
     * */
    generateColumn() {
      this.dynamicColumns = []
      var i = 0
      var j = 1
      var temp = {}
      if (this.pageCycle === 'year') {
        for (i = 0; i < this.pageForecastYear; i++) {
          temp = {}
          temp['prop'] = 'generateTitle-' + Number(this.pageStartYear + i)
          temp['label'] = Number(this.pageStartYear + i)
          this.dynamicColumns.push(temp)
        }
      }

      if (this.pageCycle === 'quarter') {
        for (i = 0; i < this.pageForecastYear; i++) {
          for (j = 1; j <= 4; j++) {
            temp = {}
            temp['prop'] = 'generateTitle-' + Number(this.pageStartYear + i) + '-Q' + j
            temp['label'] = Number(this.pageStartYear + i) + '-Q' + j
            this.dynamicColumns.push(temp)
          }
        }
      }
      if (this.pageCycle === 'month') {
        for (i = 0; i < this.pageForecastYear; i++) {
          for (j = 1; j <= 12; j++) {
            temp = {}
            temp['prop'] = 'generateTitle-' + Number(this.pageStartYear + i) + '-' + j
            temp['label'] = Number(this.pageStartYear + i) + '-' + j
            this.dynamicColumns.push(temp)
          }
        }
      }
    },
    /**
     * 格式化数字
     * */
    formatNum(num) {
      if (num === undefined || num === null || num === '' || isNaN(num)) {
        return 0
      }
      return parseFloat(num) === Infinity ? 0 : parseFloat(num)
    },
    /**
     * 打开邮箱维护界面
     * */
    emailOpenMethod() {
      this.emailOpen = true
      this.$nextTick(() => {
        this.$refs.dealIndicatorDataEmail.init(this.form.dealIndicatorEmail)
      })
    },
    /**
     * 数据填写邮箱维护中的数据, 传递给主表form
     * */
    sendEmail(data) {
      this.form.dealIndicatorEmail = data
    },
    /**
     * 指定填报页面开启
     */
    specifiedFilling() {
      this.specifiedFillingOpen = true
      this.$nextTick(() => {
        this.$refs.dealIndicatorDataAppoint.init(this.form)
        this.$refs.dealIndicatorDataAppoint.pageForecastYear = this.pageForecastYear
        this.$refs.dealIndicatorDataAppoint.pageStartYear = this.pageStartYear
        this.$refs.dealIndicatorDataAppoint.pageCycle = this.pageCycle
      })
    },
    /**
     * 解析数据交给给前台table渲染
     */
    analysisTableToVue() {
      if (this.form.dealIndicatorDataDetailList && this.dynamicColumns && this.form.operationalIndicatorsList) {
        this.form.operationalIndicatorsList.forEach((item) => {
          // indicatorId year quarter month value
          item.children && item.children.forEach(item2 => {
            var object = []
            this.form.dealIndicatorDataDetailList.some(obj => {
              if (obj.indicatorId === item2.id) {
                object.push(obj)
              }
            })
            if (object.length > 0) {
              if (this.pageCycle === 'year') {
                object.forEach(item => {
                  if (item.dataType === 'YJ') {
                    item2['generateTitle-' + item.year] = item.value
                  }
                })
              }
              if (this.pageCycle === 'quarter') {
                object.forEach(item => {
                  if (item.dataType === 'YJ') {
                    item2['generateTitle-' + item.year + '-Q' + item.quarter] = item.value
                  }
                })
              }
              if (this.pageCycle === 'month') {
                object.forEach(item => {
                  if (item.dataType === 'YJ') {
                    item2['generateTitle-' + item.year + '-' + item.month] = item.value
                  }
                })
              }
            }
          })
        })
      }
    },
    /**
     * 解析数据传递给后台
     */
    analysisTableToJava() {
      var operationalIndicatorsList = []
      this.form.operationalIndicatorsList.forEach(itemOne => {
        itemOne.children && itemOne.children.forEach(item => {
          for (var key in item) {
            if (key.includes('generateTitle-')) {
              var row = { indicatorId: item.id, dataType: 'YJ' }
              var tempField = key.split('-')
              if (tempField.length <= 2) {
                row.year = tempField[1]
                row.value = item[key]
                operationalIndicatorsList.push(row)
              } else {
                row.year = tempField[1]
                if (tempField[2].includes('Q')) {
                  // 季
                  row.quarter = tempField[2].replace('Q', '')
                } else {
                  // 月
                  row.month = tempField[2]
                }
                row.value = item[key]
                operationalIndicatorsList.push(row)
              }
            }
          }
        })
      })
      this.form.dealIndicatorDataDetailList = operationalIndicatorsList
    },
    /** 提交按钮 */
    submitForm() {
      var _this = this
      this.$confirm(this.$t('是否需要发送邮件通知?'), this.$t('提示'), {
        confirmButtonText: this.$t('发送'),
        cancelButtonText: this.$t('不发送'),
        type: 'info'
      }).then(() => {
        _this.submitFormStart(true)
      }).catch(() => {
        _this.submitFormStart(false)
      })
    },
    submitFormStart(send) {
      this.$refs['form'].validate(valid => {
        var jsonFlag = true
        if (this.form.operationalIndicatorsList === undefined || this.form.operationalIndicatorsList === null || this.form.operationalIndicatorsList.length <= 0) {
          jsonFlag = false
          this.msgError(this.$t('请生成指标数据列表'))
        }
        var emailFlag = true
        if (this.form.dealIndicatorEmail === undefined || this.form.dealIndicatorEmail === null || this.form.dealIndicatorEmail === '' || this.isEmpty(this.form.dealIndicatorEmail.email)) {
          emailFlag = false
          this.showEmailTip = true
          setTimeout(() => {
            this.showEmailTip = false
          }, 3000)
        }
        if (valid && jsonFlag && emailFlag) {
          this.loading = true
          // 解析table数据传给后台保存
          this.analysisTableToJava()
          this.form.dealIndicatorEmail.foregroundDomainName = window.location.origin
          // 整理出邮件缓存参数
          this.organizeCacheParameters()
          this.form.sendEmail = send
          saveDealIndicatorDataMain(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.init()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    organizeCacheParameters() {
      var editList = []
      for (var i = 0; i < this.form.forecastYear; i++) {
        if (this.form.cycle === 'quarter') {
          for (var j = 1; j <= 4; j++) {
            editList.push((parseInt(this.form.startYear) + i) + '-' + ('Q' + j))
          }
        } else if (this.form.cycle === 'month') {
          for (var k = 1; k <= 12; k++) {
            editList.push((parseInt(this.form.startYear) + i) + '-' + (k <= 9 ? ('0' + k) : k))
          }
        } else {
          editList.push(parseInt(this.form.startYear) + i)
        }
      }
      this.form.indicatorCache = {
        name: this.form.dealIndicatorEmail.name,
        email: this.form.dealIndicatorEmail.email,
        role: this.form.dealIndicatorEmail.role,
        userId: this.form.dealIndicatorEmail.userId,
        editList: editList
      }
    },
    isEmpty(val) {
      return !this.isNotEmpty(val)
    },
    isNotEmpty(val) {
      return val !== undefined && val !== null && val !== '' && val.length > 0
    }

  }
}
</script>

<style scoped>
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
.table-tree .el-form-item__content {
  margin-left: 0 !important;
}
.table-tree .el-form-item {
  display: inline-block;
}
/deep/ .el-table--scrollable-x .el-table__body-wrapper {
  /*overflow: auto;*/
  /*height: 450px;*/
}
</style>

